package com.module.TraceSource.dao;


import java.sql.SQLException;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import com.module.TraceSource.vo.TsKind;

import base.dao.GenericHibernateDao;
import base.util.Page;

public class TsKindDao extends GenericHibernateDao<TsKind,Long>{
	private static TsKindDao dao;
	private  TsKindDao(){
		
	}
	
	public synchronized static TsKindDao getInstance(){
		if(dao == null){
			dao = new TsKindDao();
		}
		return dao;
	}
	
	
	public Page getList(Session session,TsKind bean,Integer start, Integer limit)throws SQLException{
		Page page = new Page();
		String hql1= " from TsKind as obj where 1=1 and obj.state='000001' ";
		String hql2= " select count(*) from TsKind as obj where 1=1 and  obj.state='000001' ";
		if(bean.getName()!=null&&!"".equals(bean.getName())){
			hql1=hql1 +  " and obj.name = '"+bean.getName()+"'";
			hql2=hql2 +  " and obj.name = '"+bean.getName()+"'";
		}
		hql1 = hql1+" order by id desc";
		Query query = session.createQuery(hql1);
		query.setFirstResult(start).setMaxResults(limit);
		page.setTotal((long) ((Long) session.createQuery(hql2).uniqueResult()).intValue());
		page.setRows(query.list());	
		return page;
	}
	/**
	 * 查询所有的类别
	 * @param session
	 * @return
	 * @throws SQLException
	 */
	public List<String> getAllTsKindName(Session session)throws SQLException{
		Query query=session.createQuery(" select name from TsKind where state='000001' ");
		return query.list();
	}
	
	public Long findIdByName(Session session,String name)throws SQLException{
		Query query = session.createQuery(" select id from TsKind where state='000001' and name='"+name+"'");
		return (Long)query.uniqueResult();
	}
	/**
	 * 判断类别是否存在
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	public boolean isExist(Session session,String name,Long id ){
		StringBuffer sql = new StringBuffer(" select count(*) from TsKind where name='");
		sql.append(name).append("' and state !='000002' ");
		if(id != null && id !=0){
			sql.append(" and id !=").append(id);
		}
		Query query=session.createQuery(sql.toString());
		int n=((Long)query.uniqueResult()).intValue();
		return n>0?false:true;
	}
}
